package com.estate.framework.web.service.data;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.estate.common.core.domain.model.ApiResponse;
import com.estate.common.core.domain.model.contact.*;
import com.estate.common.utils.DateUtils;
import com.estate.common.utils.SnowflakeIdWorker;
import com.estate.framework.web.pojo.ListingFilter;
import com.estate.framework.web.service.job.ExcuteListingSchduleTask;
import com.estate.system.domain.Client;
import com.estate.system.service.impl.DataContactsServiceImpl;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class ZenuContactsApi {

    private static final Logger log = LoggerFactory.getLogger(ExcuteListingSchduleTask.class);

    @Resource
    private DataContactsServiceImpl dataContactsServiceImpl;

    @Resource
    public ZenuApiClient client;

    public void saveBatchContacts() {
//        log.info("开始保存联系人数据");
        Integer count = countNewContacts();

        // 同步数据记录
        client.syncDataRecord(count, "Contact Data", "success", "Contact", null);

        int pages = 0;
        if (count > 0) {
            pages = count % 10 == 0 ? count / 10 : count / 10 + 1;
        }
        for (int i = 0; i < pages; i++) {
            Map<String, String> filters = getListingFilter();
            List<Client> clients = pageContactsInfo(filters, i + 1, 10);
            dataContactsServiceImpl.saveBatch(clients);
        }
//        log.info("保存联系人数据结束");
    }

    @NotNull
    private static Map<String, String> getListingFilter() {
        // 获取悉尼时区
        ZoneId sydneyZone = ZoneId.of("Australia/Sydney");

        // 获取悉尼当前日期和昨天的日期
        LocalDate sydneyToday = LocalDate.now(sydneyZone);
        LocalDate sydneyYesterday = sydneyToday.minusDays(1);

        // 设置开始时间为悉尼昨天00:00:00
        String startTime = sydneyYesterday.atStartOfDay(sydneyZone).format(DateTimeFormatter.ISO_DATE_TIME);

        // 设置结束时间为悉尼今天23:59:59
        String endTime = sydneyToday.atTime(23, 59, 59).atZone(sydneyZone).format(DateTimeFormatter.ISO_DATE_TIME);

        ListingFilter filters = new ListingFilter();
        filters.setUpdatedDateFrom(startTime);
        filters.setUpdatedDateTo(endTime);
        Map<String, String> filtersMap = new HashMap<>();

        //将filter转为Map<String, String>
        filtersMap.putAll(filters.toMap());

        return filtersMap;
    }

    /**
     * 查询客户列表当天新增的数量
     *
     * @return Integer
     */
    public Integer countNewContacts() {
        try {
            Map<String, String> filters = getListingFilter();
            ApiResponse<List<ContactResp>> response = client.searchContacts(1, 1, filters);
            Long totalRecords = response.getPagination().getTotalRecords();
            return totalRecords.intValue();
        } catch (IOException e) {
            log.error("API调用失败: " + e.getMessage());
            // 同步数据记录
            client.syncDataRecord(0, "Contact Data", "failed", "Contact", e.getMessage());
        }
        return 0;
    }

    /**
     * 带过滤条件的客户列表
     *
     * @param filters    过滤条件
     * @param pageNumber 页码
     * @param pageSize   每页大小
     * @return 客户列表
     */
    public List<Client> pageContactsInfo(Map<String, String> filters, Integer pageNumber, Integer pageSize) {

        try {

            ApiResponse<List<ContactResp>> filteredResponse = client.searchContacts(pageNumber, pageSize, filters);

            if (filteredResponse.getSuccess()) {
//                log.info("========>请求成功!总记录数: {};总页数: {};当前页: {};每页大小: {}", filteredResponse.getPagination().getTotalRecords(),
//                        filteredResponse.getPagination().getTotalPages(), filteredResponse.getPagination().getPageNumber(),
//                        filteredResponse.getPagination().getPageSize());

                List<ContactResp> filteredData = filteredResponse.getData();

                //获取所有的ID
                List<Integer> ids = filteredData.stream().map(ContactResp::getId).collect(Collectors.toList());
                //查询数据库是否存在
                QueryWrapper<Client> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().in(Client::getClientId, ids);
                List<Client> existClients = dataContactsServiceImpl.list(queryWrapper);
                if (!existClients.isEmpty()) {
//                    log.info("========>数据库已存在{}条数据,跳过", existClients.size());
                    List<Integer> existIds = existClients.stream().map(Client::getClientId).collect(Collectors.toList());
                    //删除
                    dataContactsServiceImpl.remove(queryWrapper);
                    //去除filteredData中存在于existListings的数据
                    //filteredData = filteredData.stream().filter(contactResp -> !existIds.contains(contactResp.getId())).collect(Collectors.toList());
                }

                List<Client> clients = new ArrayList<>();

                for (ContactResp contactResp : filteredData) {
                    Client c = new Client();
                    c.setId(SnowflakeIdWorker.getSingleton().nextId());
                    c.setFirstName(contactResp.getFirstName());
                    c.setLastName(contactResp.getLastName());
                    c.setEmail(contactResp.getEmail());
                    c.setTitle(contactResp.getTitle());
                    c.setIsActive(contactResp.getIsActive());
                    c.setIsCompany(contactResp.getIsCompany());
                    c.setLastModified(DateUtils.parseISODate(contactResp.getLastModified()));
                    c.setAddress(JSONObject.toJSONString(contactResp.getAddress()));
                    c.setPhone(JSONObject.toJSONString(contactResp.getPhone()));
                    c.setCommunicateVia(JSONObject.toJSONString(contactResp.getCommunicateVia()));
                    c.setSource(contactResp.getSource());
                    c.setTypes(JSONObject.toJSONString(contactResp.getTypes()));
                    c.setAgents(JSONObject.toJSONString(contactResp.getAgents()));
                    c.setCriteria(JSONObject.toJSONString(contactResp.getCriteria()));
                    c.setClientId(contactResp.getId());
                    c.setCreatedAt(new Date());
                    c.setUpdatedAt(new Date());
                    clients.add(c);
                }

                return clients;
            } else {
                StringBuilder errorMsg = new StringBuilder();
                errorMsg.append("========>请求失败!\n");
                if (filteredResponse.getMessages() != null) {
                    filteredResponse.getMessages().forEach(msg -> errorMsg.append("\n").append(msg));
                }
                log.error(errorMsg.toString());
                // 同步数据记录
                client.syncDataRecord(0, "Contact Data", "failed", "Contact", errorMsg.toString());
            }

        } catch (Exception e) {
            log.error("API调用失败: " + e.getMessage());
            // 同步数据记录
            client.syncDataRecord(0, "Contact Data", "failed", "Contact", e.getMessage());
        }

        return null;
    }

    public static void main1(String[] args) {
        ZenuApiClient client = new ZenuApiClient();

        try {
            // 示例1: 搜索联系人
            System.out.println("=== 搜索联系人 ===");
            Map<String, String> filters = new HashMap<>();
            filters.put("office_id", "1");
            filters.put("is_active", "true");
            filters.put("type", "Investor");


            ApiResponse<List<ContactResp>> searchResponse = client.searchContacts(1, 10, null);
            printContacts(searchResponse);

            // 示例2: 获取单个联系人详情
            System.out.println("\n=== 获取单个联系人详情 ===");
            if (!searchResponse.getData().isEmpty()) {
                Integer firstContactId = searchResponse.getData().get(0).getId();
                ApiResponse<ContactResp> contactDetail = client.getContactById(firstContactId);
                printContactDetail(contactDetail.getData());
            }

            // 示例3: 创建联系人
            System.out.println("\n=== 创建联系人 ===");
            ContactResp newContact = createSampleContact();
            ApiResponse<ContactResp> createResponse = client.createContact(newContact);
            if (createResponse.getSuccess()) {
                System.out.println("联系人创建成功，ID: " + createResponse.getData().getId());
            }

        } catch (IOException e) {
            System.err.println("API调用失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    private static void printContacts(ApiResponse<List<ContactResp>> response) {
        if (response.getSuccess()) {
            System.out.println("请求成功!");
            System.out.println("总记录数: " + response.getPagination().getTotalRecords());
            System.out.println("总页数: " + response.getPagination().getTotalPages());
            System.out.println("当前页: " + response.getPagination().getPageNumber());
            System.out.println("每页大小: " + response.getPagination().getPageSize());

            System.out.println("\n联系人列表:");
            for (ContactResp contact : response.getData()) {
                System.out.println("---");
                System.out.println("联系人ID: " + contact.getId());
                System.out.println("姓名: " + contact.getFirstName() + " " + contact.getLastName());
                System.out.println("邮箱: " + contact.getEmail());
                System.out.println("手机: " + (contact.getPhone() != null ? contact.getPhone().getMobile() : "N/A"));
                System.out.println("类型: " + (contact.getTypes() != null ? String.join(", ", contact.getTypes()) : "N/A"));
                System.out.println("是否活跃: " + contact.getIsActive());
            }
        } else {
            System.out.println("请求失败!");
            if (response.getMessages() != null) {
                response.getMessages().forEach(System.out::println);
            }
        }
    }

    private static void printContactDetail(ContactResp contact) {
        System.out.println("=== 联系人详情 ===");
        System.out.println("ID: " + contact.getId());
        System.out.println("姓名: " + contact.getTitle() + " " + contact.getFirstName() + " " + contact.getLastName());
        System.out.println("邮箱: " + contact.getEmail());
        System.out.println("是否公司: " + contact.getIsCompany());
        System.out.println("是否活跃: " + contact.getIsActive());
        System.out.println("来源: " + contact.getSource());
        System.out.println("类型: " + (contact.getTypes() != null ? String.join(", ", contact.getTypes()) : "N/A"));

        if (contact.getAddress() != null) {
            System.out.println("地址: " + contact.getAddress().getLine1() + ", " +
                    contact.getAddress().getSuburb() + " " + contact.getAddress().getState() + " " +
                    contact.getAddress().getPostcode());
        }

        if (contact.getPhone() != null) {
            System.out.println("电话 - 手机: " + contact.getPhone().getMobile() +
                    ", 家庭: " + contact.getPhone().getHome() +
                    ", 工作: " + contact.getPhone().getWork());
        }

        if (contact.getCommunicateVia() != null) {
            System.out.println("沟通方式 - 邮件: " + contact.getCommunicateVia().getEmail() +
                    ", 电话: " + contact.getCommunicateVia().getPhone() +
                    ", 短信: " + contact.getCommunicateVia().getText());
        }

        if (contact.getCriteria() != null && !contact.getCriteria().isEmpty()) {
            System.out.println("搜索条件数量: " + contact.getCriteria().size());
            for (Criteria criteria : contact.getCriteria()) {
                System.out.println("  - 方法: " + criteria.getMethod() + ", 类别: " + criteria.getCategory());
            }
        }
    }

    private static ContactResp createSampleContact() {
        ContactResp contact = new ContactResp();
        contact.setFirstName("张");
        contact.setLastName("三");
        contact.setEmail("zhangsan@example.com");
        contact.setTitle("Mr");
        contact.setIsActive(true);
        contact.setIsCompany(false);
        contact.setSource("Web Enquiry");
        contact.setTypes(Arrays.asList("Buyer", "Investor"));

        // 设置地址
        Addr addr = new Addr();
        addr.setCountry("Australia");
        addr.setLine1("123 Example Street");
        addr.setSuburb("Melbourne");
        addr.setState("VIC");
        addr.setPostcode("3000");
        contact.setAddress(addr);

        // 设置电话
        Phone phone = new Phone();
        phone.setMobile("0400 000 000");
        phone.setHome("03 0000 0000");
        contact.setPhone(phone);

        // 设置沟通方式
        CommunicateVia communicateVia = new CommunicateVia();
        communicateVia.setEmail(true);
        communicateVia.setPhone(true);
        communicateVia.setText(false);
        contact.setCommunicateVia(communicateVia);

        return contact;
    }
}
